package org.nyt.medicalstore.controller;

import org.nyt.medicalstore.model.Customer;
import org.nyt.medicalstore.service.CustomerService;
import org.nyt.medicalstore.dto.CustomerDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/customers")
public class CustomerController {
    @Autowired
    private CustomerService customerService;

    private CustomerDTO toDTO(Customer customer) {
        if (customer == null) return null;
        CustomerDTO dto = new CustomerDTO();
        dto.setId(customer.getId());
        dto.setName(customer.getName());
        dto.setContact(customer.getContact());
        dto.setAddress(customer.getAddress());
        return dto;
    }

    @PostMapping
    public CustomerDTO addCustomer(@RequestBody Customer customer) {
        return toDTO(customerService.saveCustomer(customer));
    }

    @GetMapping("/{id}")
    public CustomerDTO getCustomer(@PathVariable Long id) {
        return toDTO(customerService.getCustomerById(id));
    }

    @GetMapping
    public List<CustomerDTO> getAllCustomers() {
        return customerService.getAllCustomers().stream().map(this::toDTO).collect(Collectors.toList());
    }

    @DeleteMapping("/{id}")
    public void deleteCustomer(@PathVariable Long id) {
        customerService.deleteCustomer(id);
    }
}
